package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //查询动态的评论列表
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1、查询互动数据（评论数据） List<Comment>
        List<Comment> list = commentApi.findComments(movementId, 2, page, pagesize);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、获取评论发布人的id，获取用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //3、一个Comment转化一个CommentVo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //4、返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    public void saveComments(String movementId, String comment) {
        //1、获取当前用户的ID
        Long userId = UserHolder.getUserId();
        //2、构造Comment对象
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(2);//评论
        comment1.setContent(comment);
        comment1.setUserId(userId);
        //3、调用API保存数据(保存数据之后，返回评论数量)
        Integer count = commentApi.save(comment1);
        System.out.println("count = " + count);
    }

    @Autowired
    private MqMessageService mqMessageService;

    //点赞
    public Integer like(String movementId) {
        //1、调用API查询是否对动态点赞
        Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),
                1);
        if(hasComment) {
            //已点赞
            throw new BusinessException(ErrorResult.likeError());
        }
        //2、调用API保存互动数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(1);//点赞
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.save(comment);
        //3、在redis中记录点赞状态  redis的数据类型：hash
        // redis的key   hashkey，hashvalue
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(redisKey,hashKey,"1");
        mqMessageService.sendLogService(UserHolder.getUserId(),"0203","movement",movementId);
        return count;
    }

    //取消点赞
    public Integer dislike(String movementId) {
        //1、判断是否已点赞，
        Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),
                1);
        if(!hasComment) {
            //未点赞，抛出异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //2、调用API删除互动数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(1);//点赞
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment); //删除互动数据
        //3、删除Redis中记录的点赞状态
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(redisKey,hashKey);
        return count;
    }
}
